﻿using OnlineCellphoneStore.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace OnlineCellphoneStore
{
    public class SearchHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // Getting the input
            string SearchInput = context.Request.QueryString["toSearch"].ToString().ToLower().Trim();
            List<DisplayObject> lDisplayObjects = new List<DisplayObject>();
            DAL.DBAdapter.CellphonesWithManuDataTable dt = SQLAdapter.GetAllCellphones();
            List<string> lAllCellphones = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                DisplayObject o = new DisplayObject();
                string Key = GenerateSearchString(row.ItemArray[2].ToString().ToLower(), row.ItemArray[1].ToString().ToLower());
                o.SearchName = Key;
                o.Id = (int)row.ItemArray[0];
                o.Name = row.ItemArray[1].ToString();
                o.Price = Double.Parse(row.ItemArray[3].ToString());
                o.Url = row.ItemArray[4].ToString();
                lDisplayObjects.Add(o);
            }
            lDisplayObjects = lDisplayObjects.FindAll(o => o.SearchName.Contains(SearchInput));
            string JsonObject = new JavaScriptSerializer().Serialize(lDisplayObjects);
            context.Response.Write(JsonObject);
        }
        private string GenerateSearchString(string Manufacturer, string Model)
        {
            string Os = "";
            string[] aAndroid = { "lg", "htc", "huawei", "samsung" };
            string[] aiOs = { "apple" };
            string[] aWindowsPhone = { "nokia" };
            if (Manufacturer.Contains("htc"))
            {
                int i = 0;
                i++;
            }
            if (aAndroid.Contains(Manufacturer))
            {
                Os = "android";
            }
            else if (aiOs.Contains(Manufacturer))
            {
                Os = "ios";
            }
            else if (aWindowsPhone.Contains(Manufacturer))
            {
                Os = "windows phone";
            }
            else
            {
                Os = "blackberry";
            }
            string Key = Os + " " + Manufacturer + " " + Model;
            return Key;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}